const express = require('express')
const path = require("path")

const materiaModel = require('../Model/materiaModel')
const LikeModel = require('../Model/LikeModel')
const collectModel = require('../Model/collectModel')
const fs = require('fs')
const multiparty = require('multiparty')
const token = require('../utils/token')
const mailModel = require('../Model/mailModel')
const router = express.Router()
//添加素材
router.post('/addMaterialData', (req, res, next) => {
    const form = new multiparty.Form({ uploadDir: 'public/images' })
    form.parse(req, async (err, fields, files) => {
        if (err) return res.json({ code: '404', msg: '文件上传失败' })
        await materiaModel.create({
            name: fields.name[0],
            types: fields.types[0],
            size: fields.size[0],
            selectData: fields.selectData[0],
            imgdomainUrl: 'http://101.32.169.227:3000' + files.img[0].path,
            imgUrl: path.resolve(__dirname, '../' + files.img[0].path),
            Url: path.resolve(__dirname, '../' + files.data[0].path)
        })
        if (fields.page[0] <= 1) {
            i = 0
        } else {
            i = (fields.page[0] - 1) * 10 - 1
        }
        const data = await materiaModel.find().skip(i).limit(10)
        const datalenth = await materiaModel.find()
        res.json({ code: '200', data, msg: datalenth.length })
    })
})
//获取素材
router.post('/getMaterialData', async (req, res, next) => {
    const { page } = req.body
    if (page <= 1) {
        i = 0
    } else {
        i = (page - 1) * 10 - 1
    }
    const data = await materiaModel.find().skip(i).limit(10)
    const datalenth = await materiaModel.find()
    res.json({ code: '200', data, msg: datalenth.length })
})
//删除素材
router.post('/deleteMaterialData', async (req, res, next) => {
    const { page, _id } = req.body
    if (page <= 1) {
        i = 0
    } else {
        i = (page - 1) * 10 - 1
    }
    const deletedata = await materiaModel.findOne({ _id })
    fs.unlinkSync(deletedata.Url)
    fs.unlinkSync(deletedata.imgUrl)
    await materiaModel.deleteOne({ _id })
    await LikeModel.deleteOne({ Material: _id })
    await collectModel.deleteOne({ Material: _id })
    const data = await materiaModel.find().skip(i).limit(10)
    const datalenth = await materiaModel.find()
    res.json({ code: '200', data, msg: datalenth.length })
})

//获取4个首页数据
router.post('/getMaterial', async (req, res, next) => {
    const data = [
        ...await materiaModel.find({ selectData: '人物' }),
        ...await materiaModel.find({ selectData: '武器' }),
        ...await materiaModel.find({ selectData: '地图' }),
        ...await materiaModel.find({ selectData: '物品' })
    ]
    res.json({ code: '200', data })
})
//获取详情数据
router.post('/getDetailsMaterial', async (req, res, next) => {
    const { _id } = req.body
    const data = await materiaModel.findOne({ _id })
    res.json({ code: '200', data })
})
//随机获取4个数据
router.post('/getRandomDetailsMaterial', async (req, res, next) => {

    const data = await materiaModel.aggregate([
        { $sample: { size: 4 } }
    ]);
    res.json({ code: '200', data })
})

//搜索的标题数据
router.post('/getTitleMaterial', async (req, res, next) => {
    const { title } = req.body
    const data = await materiaModel.find({ selectData: title });
    res.json({ code: '200', data })
})

//切换页面
router.post('/tabPage', async (req, res, next) => {
    const { page } = req.body
    if (page <= 1) {
        i = 0
    } else {
        i = (page - 1) * 10
    }
    const data = await materiaModel.find().skip(i).limit(10)
    res.json({ code: '200', data })
})

//修改数据
router.post('/upDataMaterial', async (req, res, next) => {
    const { page, _id, upData } = req.body
    if (page <= 1) {
        i = 0
    } else {
        i = (page - 1) * 10
    }
    await materiaModel.updateOne({ _id }, { types: upData })
    const data = await materiaModel.find().skip(i).limit(10)
    res.json({ code: '200', data })
})

//查询素材
router.post('/searchMaterial', async (req, res, next) => {
    const { name } = req.body
    const data = await materiaModel.find({ name: { $regex: name, $options: 'i' } })
    res.json({ code: '200', data })
})

//下载素材
router.post('/download',token, async (req, res) => {
    const { id, mail } = req.body
    const mailer = await mailModel.findOne({ _id: mail })
    const data = await materiaModel.findOne({ _id: id })
    if (mailer.frequency >= data.types) {
        const newFrequency = mailer.frequency - data.types
        await mailModel.updateOne({_id: mail},{frequency:newFrequency})
        res.download(data.Url, (err) => {
            if (err) {
                res.send('200')
                return
            }
        })
        return
    }
    res.send('200')
})
//获取最后十条数据
router.post('/getDataMaterial', async (req, res) => {
    const data = await materiaModel.find().sort({ _id: -1 }).limit(10)
    res.json({code:'200',data})
})
//获取素材
router.post('/selectPCGetMaterial', async (req, res, next) => {
    const data = await materiaModel.find()
    res.json({ code: '200', data })
})


module.exports = router